<template>
  <div>
    <van-nav-bar fixed>
      <template #left>
        <img class="logo" :src="img" alt="" />
      </template>
      <template #right>
        <van-icon name="search" size="0.48rem" color="#fff" @click="$router.push('/search')"/>
      </template>
    </van-nav-bar>
    <van-tabs v-model="channelId" animated sticky offset-top="1.226667rem">
      <van-tab
        v-for="item in UserChannelList"
        :title="item.name"
        :key="item.id"
        :name="item.id"
      >
        <ArticleList :cid="channelId" ></ArticleList>
      </van-tab>
    </van-tabs>
    <van-icon
      name="plus"
      size="0.37333334rem"
      class="moreChannels"
      @click="show = true"
    />
    <!-- 弹出层组件 -->
    <van-popup v-model="show" class="edit_wrap" @closed="onPopupClosed">
      <!-- 弹出层的主体区域 -->
      <channel-edit
        :userChannelList="UserChannelList"
        @close="show = false"
        @addChannel="addChannelFn"
        @removeChannel="removeChannelFn"
        @changeChannel = "changeChannelFn"
        ref="channelEdit"
      ></channel-edit>
    </van-popup>
  </div>
</template>

<script>
import ArticleList from '@/views/Home/ArticleList.vue'
import ChannelEdit from './ChannelEdit.vue'
import { userChannelAPI, updateChannelAPI } from '@/api'
import imgLogo from '../../assets/toutiao_logo.png'
export default {
  data () {
    return {
      img: imgLogo,
      channelId: 0,
      UserChannelList: [],
      show: false
    }
  },
  methods: {
    async updateChannelAPI () {
      const list = this.UserChannelList.filter((item) => {
        return item.id !== 0
      })
      const resArr = list.map((item, index) => {
        const newObj = { ...item }
        newObj.seq = index + 1
        delete newObj.name
        return newObj
      })
      await updateChannelAPI({
        channels: resArr
      })
    },
    // 进入频道
    changeChannelFn (val) {
      this.channelId = val.id
    },
    onPopupClosed () {
      this.$refs.channelEdit.isEdit = false
    },
    async addChannelFn (val) {
      this.UserChannelList.push(val)
      this.updateChannelAPI()
    },
    removeChannelFn (val) {
      const index = this.UserChannelList.findIndex(
        (item) => item.id === val.id
      )
      this.UserChannelList.splice(index, 1)
      this.updateChannelAPI()
    }
  },
  async created () {
    const res = await userChannelAPI()
    const { channels } = res.data.data
    this.UserChannelList = channels
  },
  components: {
    ArticleList,
    ChannelEdit
  }
}
</script>

<style scoped lang="less">
.logo {
  width: 100px;
  height: 30px;
}
/* tab内容距离tab导航的距离 */
/deep/ .van-tabs__content {
  padding-top: 44px;
}
// 设置 tabs 容器的样式
/deep/ .van-tabs__wrap {
  padding-right: 30px;
  background-color: #fff;
}

// 设置小图标的样式
.moreChannels {
  position: fixed;
  top: 62px;
  right: 8px;
  z-index: 999;
}
/* 频道编辑弹出层铺满屏幕 */
.edit_wrap {
  width: 100%;
  height: 100%;
}
</style>
